package com.lwl.blog.system.config;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.ParserConfig;

import javax.annotation.PostConstruct;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

//@Configuration
public class JSONConfiguration {
    @PostConstruct
    public void init() {
        ParserConfig.getGlobalInstance().putDeserializer(LocalDate.class, (com.alibaba.fastjson.parser.deserializer.ObjectDeserializer) new LocalDateDeserializer());
        ParserConfig.getGlobalInstance().putDeserializer(LocalDateTime.class, (com.alibaba.fastjson.parser.deserializer.ObjectDeserializer) new LocalDateDeserializer());
    }

    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy.MM.dd");

    /**
     * LocalDate从JSON字符串反序列化类
     *
     **/
    public static class LocalDateDeserializer implements com.alibaba.fastjson.parser.deserializer.ObjectDeserializer {
        @Override
        public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
            // 如果是字符串格式
            parser.getLexer().nextToken();
            String value = parser.getLexer().stringVal();
            if (value.contains("-")) {
                if (type.equals(LocalDateTime.class)) {
                    return (T) LocalDate.parse(value, dateTimeFormatter).atStartOfDay();
                } else {
                    return (T) LocalDate.parse(value, dateTimeFormatter);
                }
            } else if (value.contains(".")) {
                if (type.equals(LocalDateTime.class)) {
                    return (T) LocalDateTime.parse(value, dateTimeFormatter1);
                } else {
                    return (T) LocalDate.parse(value, dateTimeFormatter1);
                }
            }

            long longValue = Long.parseLong(value) / 1000;
            if (type.equals(LocalDateTime.class)) {
                return (T) LocalDateTime.ofEpochSecond(longValue, 0, ZoneOffset.ofHours(8));
            } else if (type.equals(LocalDate.class)) {
                return (T) LocalDateTime.ofEpochSecond(longValue, 0, ZoneOffset.ofHours(8)).toLocalDate();
            }

            return null;
        }

        @Override
        public int getFastMatchToken() {
            return 0;
        }
    }
}
